//
//  SinaHomeViewController.m
//  MySinaWeiboProjectForOC
//
//  Created by apple on 2016/11/12.
//  Copyright © 2016年 WangChen. All rights reserved.
//

#import "SinaHomeViewController.h"
#import "UIBarButtonItem+extension.h"
#import "SinaDemoViewController.h"
#import "SinaUserAccountViewModel.h"
#import "SinaHomeViewModel.h"
#import "SinaHomeCell.h"
#import <SVProgressHUD.h>
#import "MyAFNTools.h"
#import <YYModel.h>
#import "SinaHomeCustomRefreshView.h"
#import "SinaHomeRefreshCountBar.h"

@interface SinaHomeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) SinaHomeViewModel *homeViewModel;
@property (nonatomic,weak) UIActivityIndicatorView *refreshIndecator;
@property (nonatomic,weak) SinaHomeRefreshCountBar *refreshCountBar;

@end


static NSString *cellid = @"cellid";
static NSString *retweeteCellID = @"SinaHomeRetweeteCellid";

@implementation SinaHomeViewController

#pragma mark
#pragma mark - 懒加载homeViewModel
-(SinaHomeViewModel *)homeViewModel{
    if(!_homeViewModel){
        _homeViewModel = [[SinaHomeViewModel alloc]init];
    }
    return _homeViewModel;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //如果未登录
    if(![SinaUserAccountViewModel shared].isLogin){
    [self.visitorView updateInfoWithTitle:@"点击登录卧了个槽了哈哈哈哈哈哈哈哈哈哈哈哈~~~" imageName:@"visitordiscover_feed_image_smallicon" isHome:YES];
    }else{
        //如果已登录
        [self setupTableViewUI];
        
        //在tableViewFooter设置菊花
        [self setupIndicator];
        
        //自定义下拉刷新控件
        [self setupRefreshView];
        
        //下拉刷新提示
        [self setupRefreshCountBar];
        
        //加载数据
        [self loadData];
        
        //注册通知
        [self registNotification];
    }
    
    
    
    [self setupUI];
    
}

#pragma mark
#pragma mark - 布置界面
- (void)setupUI{
    
    //设置右上角按钮
    [self setRightBtnItem];
    
    
}

#pragma mark
#pragma mark - 注册通知
-(void)registNotification{
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getNotificationRefresh) name:kNotificationRefreshHomePage object:nil];
    
}



#pragma mark
#pragma mark - 布置tableView界面
-(void)setupTableViewUI{
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 400;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    UINib *nib = [UINib nibWithNibName:@"SinaHomeCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:cellid];
    
    UINib *retweetweNib = [UINib nibWithNibName:@"SinaHomeRetweeteCell" bundle:nil];
    [self.tableView registerNib:retweetweNib forCellReuseIdentifier:retweeteCellID];
}


#pragma mark
#pragma mark - 自定义下拉刷新控件
-(void)setupRefreshView{
    SinaHomeCustomRefreshView *customRefreshView = [[SinaHomeCustomRefreshView alloc]init];
    [self.tableView addSubview:customRefreshView];
    customRefreshView.frame = CGRectMake(0, -kCustomRefreshHeight, kScreenWidth, kCustomRefreshHeight);
    
    //添加监听
    [customRefreshView addTarget:self action:@selector(pullDownRefresh:) forControlEvents:UIControlEventValueChanged];
    
}

#pragma mark
#pragma mark - 提示下拉刷新数据条数
-(void)setupRefreshCountBar{
    SinaHomeRefreshCountBar *refreshCountBar = [[SinaHomeRefreshCountBar alloc]init];
    
    [self.navigationController.view insertSubview:refreshCountBar belowSubview:self.navigationController.navigationBar];
    
    _refreshCountBar = refreshCountBar;
    
    refreshCountBar.frame = CGRectMake(0,kGuideBarHeight - 44, kScreenWidth, 44);
    
    refreshCountBar.hidden = YES;
    
    
}


#pragma mark
#pragma mark - 得到刷新通知触发方法
-(void)getNotificationRefresh{
    [self.homeViewModel loadWeiboDataWithIsPullUp:NO finishBlock:^(BOOL isSuccess, NSInteger refreshCount) {
        if(!isSuccess){
            [SVProgressHUD showErrorWithStatus:@"世界上最远的距离就是米有网络"];
            
            return;
        }
        
        [SVProgressHUD showSuccessWithStatus:@"刷新成功~"];
        
        [self refreshCountBarAnimWithCount:refreshCount];
        
        [self.tableView reloadData];
    }];
}



#pragma mark
#pragma mark - 下拉刷新触发方法
-(void)pullDownRefresh:(SinaHomeCustomRefreshView *)sender{
    [self.homeViewModel loadWeiboDataWithIsPullUp:NO finishBlock:^(BOOL isSuccess, NSInteger refreshCount) {
        if(!isSuccess){
            [SVProgressHUD showErrorWithStatus:@"世界上最远的距离就是米有网络"];
            [sender endRefreshing];
            return;
        }
        
        [SVProgressHUD showSuccessWithStatus:@"刷新成功~"];
        
        [sender endRefreshing];
        
        [self refreshCountBarAnimWithCount:refreshCount];
        
        [self.tableView reloadData];
    }];
}


#pragma mark
#pragma mark - 提示条动画
-(void)refreshCountBarAnimWithCount:(NSInteger)count{
    
    self.refreshCountBar.hidden = NO;
    self.refreshCountBar.refreshCount = count;
    self.refreshCountBar.alpha = 1;
    
    [UIView animateWithDuration:0.5 animations:^{
        self.refreshCountBar.transform = CGAffineTransformMakeTranslation(0, 44);
    }completion:^(BOOL finished) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.5 animations:^{
                self.refreshCountBar.transform = CGAffineTransformIdentity;
                self.refreshCountBar.alpha = 0;
            }completion:^(BOOL finished) {
                self.refreshCountBar.hidden = YES;
            }];
        });
    }];

    
    
}



#pragma mark
#pragma mark - 在TableView  footer上添加菊花
-(void)setupIndicator{
    
    UIActivityIndicatorView *refreshIndecator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
    self.tableView.tableFooterView = refreshIndecator;
    
    self.refreshIndecator = refreshIndecator;
    
}


#pragma mark
#pragma mark - 加载数据
-(void)loadData{
    
    [self.homeViewModel loadWeiboDataWithIsPullUp:NO finishBlock:^(BOOL isSuccess, NSInteger refreshCount) {
        if(!isSuccess){
            [SVProgressHUD showErrorWithStatus:@"世界上最远的距离就是没有网络"];
            return ;
        }
        [self refreshCountBarAnimWithCount:refreshCount];
        [self.tableView reloadData];
    }];
}


#pragma mark
#pragma mark - 设置右上角按钮
- (void)setRightBtnItem{
    
    UIBarButtonItem *btnItem = [[UIBarButtonItem alloc]initWithTitle:nil image:@"navigationbar_pop" addTarget:self action:@selector(clickPopBtn)];
    
    self.navigationItem.rightBarButtonItem = btnItem;
}


#pragma mark
#pragma mark - 点击右上角按钮监听方法
- (void)clickPopBtn{
    
    SinaDemoViewController *demoVC = [[SinaDemoViewController alloc]init];
    
    [self.navigationController pushViewController:demoVC animated:YES];
    
}




#pragma mark
#pragma mark - tableView数据源
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.homeViewModel.homeCellViewModelList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *theCellId = cellid;
    if(self.homeViewModel.homeCellViewModelList[indexPath.row].homeCellModel.retweeted_status != nil){
        theCellId = retweeteCellID;
    }
    
    SinaHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:theCellId forIndexPath:indexPath];
    cell.homeCellViewModel = self.homeViewModel.homeCellViewModelList[indexPath.row];
    return cell;
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SinaHomeCellModel *model = _homeViewModel.homeCellViewModelList[indexPath.row].homeCellModel;
    NSString *nibName = [self getNibNameWithModel:model];
    SinaHomeCell *cell = [[UINib nibWithNibName:nibName bundle:nil] instantiateWithOwner:nil options:nil].lastObject;
    cell.homeCellViewModel = self.homeViewModel.homeCellViewModelList[indexPath.row];
    [cell.contentView layoutIfNeeded];
    return cell.toolBarView.frame.origin.y + 35;
}



-(NSString *)getNibNameWithModel:(SinaHomeCellModel*)model{
    
    if(model.retweeted_status != nil){
        return @"SinaHomeRetweeteCell";
    }else{
        return @"SinaHomeCell";
    }
    
}


#pragma mark
#pragma mark - cell将要显示时触发上拉加载更多
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //到了倒数第二个cell  开始加载数据
    if(![self.refreshIndecator isAnimating]){
        
        if(indexPath.row == self.homeViewModel.homeCellViewModelList.count - 2){
            //菊花开始转动
            [self.refreshIndecator startAnimating];
            
            //加载数据
            [self.homeViewModel loadWeiboDataWithIsPullUp:YES finishBlock:^(BOOL isSuccess, NSInteger refreshCount) {
                if(!isSuccess){
                    [SVProgressHUD showErrorWithStatus:@"世界上最远的距离就是没有网络..."];
                    return;
                }
                
                //数据加载成功
                [self.refreshIndecator stopAnimating];
                
                
                [self.tableView reloadData];

            }];
            
        }
    }
}



@end
